<?php

namespace App\Server\Upload;

class Index
{
    private $curlImageUpload;
    private $curlImageUrl='';
    
    public function __construct()
    {
        $this->curlImageUpload = new \App\Server\Util\CurlImageUpload;
        $this->curlImageUrl = "http://upload.11angle.net/image_upload/other/ImageUpload.php";
    }

    public function init($folder, $tmpName, $fileType="image/png", $ext="png")
    {
        $newName = time() . rand(10000, 99999) . '.' . $ext;
        $bool = $this->curlImageUpload->CURLPOST($tmpName, $fileType, $newName, $folder, $this->curlImageUrl);
        if(empty($bool)){
            throw new \Exception(json_encode('error', ...config('api.error.uploadErr')));
        }
        return "//wwwimageup.fusoft001.com/other/{$folder}/{$newName}";
    }

    public function h5UploadParams(){
        $folder = Request()->folder ?: 'MF_laravel';
        $file = $_FILES['file'] ?: null;
        if(empty($file['name'])){
            return $this->mResponse(null, ...config('api.error.uploadParams'));
        }
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $this->fileSizeLimitValidate($file['size']);
        $this->fileExtValidate($file['name']);
        return [$folder, $file['tmp_name'], $file['type'], $ext];
    }

    private function fileSizeLimitValidate($imgSize)
    {
        $maxSize = 50;
        $imgSize /= 1000 * 1000;
        if($imgSize > $maxSize){
            throw new \Exception(json_encode('error', ...config('api.error.uploadSizeLimit')));
        }
    }

    private function fileExtValidate($fileName)
    {
        $extLegel = false;
        $uploadFileExt = [
            "doc", "docx", "xls", "xlsx", 
            "jpg", "jpeg", "gif", "webp", "png", 
            "mp4", "rar", "pdf", 
        ];
        foreach ($uploadFileExt as $item) {
            if (strpos($fileName, $item) !== false) {
                $extLegel = true;
                break;
            }
        }
        if (!$extLegel) {
            return $this->mResponse(null, ...config('api.error.uploadExt'));
        }
    }

}